import { useState } from "react";
import { useQueryClient, useMutation } from "@tanstack/react-query";

import { postTodo } from "./store";

export default function AddTodo() {
  const queryClient = useQueryClient();
  const [name, setName] = useState("");

  const addMutation = useMutation({
    mutationFn: postTodo,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["todos"] });
    },
  });

  return (
    <div>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        disabled={addMutation.status === "loading"}
      />
      <button
        onClick={() => {
          addMutation.mutate({ name });
        }}
        disabled={addMutation.status === "loading" || !name}
      >
        Add Todo
      </button>
      <div>
        {addMutation.status === "loading"
          ? "Saving..."
          : addMutation.status === "error"
          ? addMutation.error.message
          : "Saved!"}
      </div>
    </div>
  );
}
